import 'package:bubble/bubble.dart';
import 'package:event_bus/event_bus.dart';
import 'package:flutter/material.dart';
import 'package:flutter_shark_im/component/head_bubble.dart';
import 'package:flutter_shark_im/entity/message/base_message_entity.dart';
import 'package:flutter_shark_im/entity/message/user_list_response_entity.dart';
import 'package:flutter_shark_im/main.dart';
import 'package:flutter_shark_im/util/date_util.dart';

class Chat extends StatefulWidget {

  final EventBus eventBus;

  final User _user;

  Chat(this.eventBus, this._user);

  @override
  State<StatefulWidget> createState() => ChatState(_user);

}

class ChatState extends State<Chat> {

  static double px;

  /// _messageList 用户对话列表
  final  _messageList = <Message>[];

  /// 对话用户
  final User _chatUser;

  /// pageNo 当前页面
  /// pageSize 每页数量
  int pageNo = 0, pageSize = 15;

  /// 滚动
  final _listScrollController =  ScrollController();

  /// 消息文本
  final _textController = TextEditingController();

  ChatState(this._chatUser,);

  @override
  void initState() {
    _getMessage();
    _jumpBottom();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    if (px == null) {
      double pixelRatio = MediaQuery.of(context).devicePixelRatio;
      px = 1 / pixelRatio;
      BubbleStyleConfig.init();
    }

    return Scaffold(
      appBar: AppBar(
        title: Text(_chatUser.name),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.sort),
            onPressed: () => {
              _jumpBottom()
            },
          )
        ],
      ),
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          Container(
            child: Flexible(
              child: _listView(),
            ),
          ),
          Divider(height: 2.0),
          Container(
            height: 50,
            padding: EdgeInsets.all(10),
            child: _bottomTool(),
          )
        ],
      ),
    );
  }

  _listView() {
    return ListView.builder(
      controller: _listScrollController,
      itemCount: _messageList.length,
      itemBuilder: (context, index) {
        final message = _messageList[index];
        if (message.time == null) {
          return Bubble(
            style: BubbleStyleConfig.styleTime,
            child: Text(message.content, style: TextStyle(fontSize: 10)),
          );
        } else {
          return HeadBubble(
            style: message.isMe ? BubbleStyleConfig.styleMe : BubbleStyleConfig.styleSomebody,
            content: message.content,
            me: SharkIm.avatar.toString(),
            someBody: _chatUser.avatar,
          );
        }
      },
    );
  }

  /// 底部状态来
  _bottomTool() {
    return Row(
      children: <Widget>[
        new Flexible(
            child: new TextField(
              controller: _textController,
              decoration: InputDecoration.collapsed(hintText: '发送消息'),
              onChanged: (content) {
                setState(() {
                  _textController.text;
                });
              },
              onTap: () {
                _jumpBottom();
              },
            )
        ),
        new Container(
          color: _textController.text.isEmpty ? Colors.black26 : Colors.blue,
          margin: EdgeInsets.symmetric(horizontal: 4.0),
          child: MaterialButton(
            child: Text(
              '发送',
              style: TextStyle(color: Colors.white),
            ),
            onPressed: () {
              if (_textController.text.isNotEmpty) {
                setState(() {
                  _sendMessage(_textController.text);
                  _jumpBottom();
                });
              }
            },
          ),
        )
      ],
    );
  }

  /// 发送消息
  _sendMessage(String content) {
    final sendMsg = Message(isMe: true, content: _textController.text, time: DateTime.now());
    debugPrint('Send message: $sendMsg}');
    _addMessage(sendMsg);
    widget.eventBus.fire(sendMsg);
    _textController.text = '';
  }


  /// 底部跳转方法
  _jumpBottom({double now}) {
    WidgetsBinding.instance.addPostFrameCallback((time) {
      return _listScrollController.jumpTo(_listScrollController.position.maxScrollExtent);
    });
  }

  /// 获取聊天列表
  _getMessage() {
    final items = SharkIm.getMessageList(_chatUser.id, pageNo, pageSize);
    for(int i=0; i!=items.length; i++) {
      _addMessage(items[i]);
    }
  }

  _addMessage(Message message) {
    final timeMessage = _evaluateTime(message.time);
    if (timeMessage != null) {
      _messageList.add(timeMessage);
    }
    _messageList.add(message);
  }

  /// 间隔计算
  _evaluateTime(DateTime current) {
    DateTime before = _messageList.isEmpty ? null : _messageList.last.time;
    if (before != null && before.difference(current).inMinutes < 5) return null;

    String time;
    int hour = current.hour;
    if (hour >= 0 && hour < 12) {
      time = '早上';
    } else if (hour >= 12 && hour < 13) {
      time = '中午';
    } else if (hour >= 13 && hour < 18) {
      time = '下午';
    } else if (hour >= 18 && hour < 24) {
      time = '晚上';
    }
    return Message(content: time +
        ' ${DateUtil.twoDigits(current.hour)}:${DateUtil.twoDigits(current.minute)}');
  }

}

/// 聊天气泡样式配置
class BubbleStyleConfig {

  static BubbleStyle styleSomebody;

  static BubbleStyle styleMe;

  static BubbleStyle styleTime;

  static init() {
    double px = ChatState.px;

    styleSomebody = BubbleStyle(
      nip: BubbleNip.leftTop,
      color: Colors.white,
      elevation: 1 * px,
      margin: BubbleEdges.only(top: 8.0, right: 50.0),
      alignment: Alignment.topLeft,
    );

    styleMe = BubbleStyle(
      nip: BubbleNip.rightTop,
      color: Color.fromARGB(255, 225, 255, 199),
      elevation: 1 * px,
      margin: BubbleEdges.only(top: 8.0, left: 50.0),
      alignment: Alignment.topRight,
    );

    styleTime = BubbleStyle(
      alignment: Alignment.center,
      color: Color.fromARGB(255, 212, 234, 244),
      elevation: 1 * px,
      margin: BubbleEdges.only(top: 8.0),
    );
  }
}